//###############
//FILE : Communication.java
//WRITER : Daniel Lowengrub, daniel_i_l, 320687098
//EXERCISE : oop ex3 2011
//DESCRIPTION:
//See below
//###############


package oop.ex3.communication;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * This class provides general communication functionality used throughout the project.
 * Mostly operations that deal with opening and closing sockets and streams.
 * @author daniel
 */
public class Communication {
    public static final int TIMEOUT = 5000;
    public static String getLocalIp() throws UnknownHostException{
        return InetAddress.getLocalHost().getHostAddress();
    }

    /**
     * Creates a data input stream from  socket.
     * @param socket The socket to use.
     * @return The data input stream.
     * @throws java.io.IOException If the stream souldn't be created.
     */
    public static DataInputStream getInputStreamFromSocket(Socket socket) throws IOException {
        BufferedInputStream bufIn = new BufferedInputStream(socket.getInputStream());
        return new DataInputStream(bufIn);
    }

    /**
     * Creates a data output stream from  socket.
     * @param socket The socket to use.
     * @return The data output stream.
     * @throws java.io.IOException If the stream souldn't be created.
     */
    public static DataOutputStream getOutputStreamFromSocket(Socket socket) throws IOException {
        BufferedOutputStream bufOut = new BufferedOutputStream(socket.getOutputStream());
        return new DataOutputStream(bufOut);
    }

    /**
     * Creates a server socket that listens to a specific port. It's initialized with
     * the parameters specified in the assignment.
     * @param port The port to listen to.
     * @return The server socket.
     * @throws java.io.IOException If the socket couldn't be created.
     */
    public static ServerSocket getServerSocket(int port) throws IOException {
        ServerSocket socket = new ServerSocket(port);
        socket.setSoTimeout(TIMEOUT);
        return socket;
    }

    /**
     * Creates a socket that listens to a specific port. It's initialized with
     * the parameters specified in the assignment.
     * @param port The port to listen to.
     * @return The server socket.
     * @throws java.io.IOException If the socket couldn't be created.
     */
    public static Socket getSocket(SocketAddress address) throws IOException {
        Socket socket = new Socket(address.getIp(), address.getPort());
        socket.setSoTimeout(TIMEOUT);
        return socket;
    }

}
